package cn.wolfcode.web.interceptor;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.utli.RequiredPermission;
import cn.wolfcode.utli.UserCountext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class CheckPermissionInterceptor implements HandlerInterceptor {
    @Autowired
    private IPermissionService permissionService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws
            Exception {
        //获取session对象
        Employee employee = (Employee) request.getSession().getAttribute("EMPLOYEE_IN_SESSION");
        if (employee.getAdmin()) {
            //是管理员就进
            return true;
        }
        // 若不是管理员，获取当前要执行的控制器的处理方法
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        RequiredPermission annotation = handlerMethod.getMethodAnnotation(RequiredPermission.class);
        //如果没有贴注解 就放行
        if (annotation == null) {
            return true;
        }
        // 若贴了权限注解，通过权限注解获取权限表达式
        String expression = annotation.expression();
        //获取当前登录用户拥有的权限 List<String>
        List<String> expressions = UserCountext.getExpression();
        if (expressions.contains(expression)) {
            return true;
        }
        // 转发到没权限的提示页面
        request.getRequestDispatcher("/WEB-INF/views/common/nopermission.jsp")
                .forward(request, response);

        return false;
    }
}
